﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Timers;
using System.Runtime.InteropServices;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Configuration;
using System.Text.RegularExpressions;
using EnglishStemmer;
using RussianStemmer;
using System.Diagnostics;


namespace TxM
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public void NewFile()
        {

        }

        public void DeleteFile(string id)
        {
            RemoveAllDocRelated(id);
            QE("delete from Docs where id='" + id + "'");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            GetDocs();
        }
        public void GetDocs()
        {
            QToDv("SELECT id,path FROM dbo.Docs");
        }

        public void QToView(string p) { QueryToDv(p,view); }
        public void QToDv(string p) { QueryToDv(p,dv); }
        public int QE(string p) { return QueryExecute(p); }
        public object QS(string p) { return QueryScalar(p); }
        public object[] QArr(string p) { return QueryArray(p); }

        public void QueryToDv(string p,DataGridView dv)
        {
            string strConnection = ConfigurationSettings.AppSettings["CustomizationStrings"];

            SqlConnection Connection = new SqlConnection(strConnection);
            Connection.Open();
            String strSQL = p;
            SqlCommand command = new SqlCommand(strSQL, Connection);


            SqlDataReader reader = command.ExecuteReader();
            //string naimenovanie = "";
            //while (reader.Read())
            //{
            //    naimenovanie = reader.GetString(0) + " " + reader.GetInt32(1).ToString();
            //    comboBox1.Items.Add(naimenovanie);
            //}
            DataTable table = new DataTable();
            table.Load(reader);
            reader.Close();
            dv.DataSource = table;
            Connection.Close();

            SizeAll(dv);
        }

        public void SizeAll(DataGridView dv)
        {
            SizeColumnsToContent(dv, -1);
            dv.RowHeadersVisible = false;
        }

        public void SizeColumnsToContent(DataGridView dataGrid, int nRowsToScan)
        {
            Graphics g = dataGrid.CreateGraphics();
            try
            {
                DataTable dataTable = (DataTable)dataGrid.DataSource;
                if (-1 == nRowsToScan)
                {
                    nRowsToScan = dataTable.Rows.Count;
                }

                //foreach (DataGridViewColumn c in dataGrid.Columns)
                for (int iCurrCol = 0; iCurrCol < dataGrid.Columns.Count; iCurrCol++)
                {
                    DataGridViewColumn c = dataGrid.Columns[iCurrCol];
                    // Set width to header text width.
                    int iWidth = (int)(g.MeasureString(c.HeaderCell.Value.ToString(), dataGrid.Font).Width);
                    // Change width, if data width is wider than header text width.
                    // Check the width of the data in the first X rows.
                    DataRow dataRow;
                    for (int iRow = 0; iRow < nRowsToScan; iRow++)
                    {
                        dataRow = dataTable.Rows[iRow];

                        if (null != dataRow[c.Name])
                        {
                            int iColWidth = (int)(g.MeasureString(dataRow.ItemArray[iCurrCol].ToString(), dataGrid.Font).Width);
                            iWidth = (int)System.Math.Max(iWidth, iColWidth);
                        }
                    }

                    if (c.Name == "id") c.Width = 1;
                    else
                        c.Width = iWidth + 10;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            finally
            {
                g.Dispose();
            }
        }

        public string[] QueryToLines(string p)
        {
            string strConnection = ConfigurationSettings.AppSettings["CustomizationStrings"];
            SqlConnection Connection = new SqlConnection(strConnection);
            Connection.Open();
            String strSQL = p;
            SqlCommand command = new SqlCommand(strSQL, Connection);
            SqlDataReader reader = command.ExecuteReader();
            DataTable table = new DataTable();
            table.Load(reader);
            
            //dv.DataSource = table;
            string[] res = new string[table.Rows.Count];
            //foreach (DataRow dr in table.Rows)
            for (int i = 0; i < table.Rows.Count; i++)
            {
                DataRow dr = table.Rows[i];
                res[i] = dr.ItemArray[0].ToString();
            }
            reader.Close();

            Connection.Close();
            return res;
        }

        public DataTable QueryTable(string p)
        {
            string strConnection = ConfigurationSettings.AppSettings["CustomizationStrings"];
            SqlConnection Connection = new SqlConnection(strConnection);
            Connection.Open();
            String strSQL = p;
            SqlCommand command = new SqlCommand(strSQL, Connection);
            SqlDataReader reader = command.ExecuteReader();
            DataTable table = new DataTable();
            table.Load(reader);
            reader.Close();

            Connection.Close();
            return table;
        }

        public int QueryExecute(string p)
        {
            string strConnection = ConfigurationSettings.AppSettings["CustomizationStrings"];

            SqlConnection Connection = new SqlConnection(strConnection);
            Connection.Open();
            String strSQL = p;
            SqlCommand command = new SqlCommand(strSQL, Connection);

            int rowsaffected = command.ExecuteNonQuery();
            Connection.Close();
            return rowsaffected;
        }

        public object QueryScalar(string p)
        {
            string strConnection = ConfigurationSettings.AppSettings["CustomizationStrings"];

            SqlConnection Connection = new SqlConnection(strConnection);
            Connection.Open();
            String strSQL = p;
            SqlCommand command = new SqlCommand(strSQL, Connection);

            object rowsaffected = command.ExecuteScalar();
            Connection.Close();
            return rowsaffected;
        }

        public object[] QueryArray(string p)
        {
            return QueryToLines(p);
        }

        public int NewDoc(string p)
        {
            object was = QS("select COUNT(id) from Docs where path='" + p + "'");
            int id = 0;
            if ((int)was == 0)
            {
                QE("insert into Docs(path) VALUES('" + p + "')");
                was = QS("select MAX(id) from Docs where path='" + p + "'");
                id = (int)was;
            }
            return id;
        }







        int docid = 1;
        string tmp_path = "";
        public void RtfOpener(string path)
        {

            docid = NewDoc(path);
            TxtOpener(tmp_path);
        }

        public void TxtOpener(string path)
        {

        }

        public void DocOpener(string path)
        {
        }

        public void PdfOpener(string path)
        {
        }

        public void AddFile(string FileName)
        {
            //FileInfo ei = new FileInfo(FileName);
            //if (ei.Extension==".pdf")
            //{
            //    PdfOpener(FileName);
            //}
            //if (ei.Extension == ".doc")
            //{
            //    alert(NewDoc(FileName));
            //    //DocOpener(FileName);
            //}
            //if (ei.Extension == ".rtf")
            //{
            //    RtfOpener(FileName);
            //}
            //if (ei.Extension == ".txt")
            //{
            //    TxtOpener(FileName);
            //}
            XReader oReader = new XReader(FileName);
            //richTextBox1.Text = oReader.Text;
            string xs = oReader.Text;
            string uidoc = NewDoc(FileName, xs);
            InsertInfo(uidoc);
            RemoveAllDocRelated(uidoc);
            Parse(oReader.Text, uidoc);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                DoOpenBase(openFileDialog1.FileName);
                GetDocs();
            }
        }


        string[] maner = { ".pdf", ".doc", ".txt", ".rtf" };
        public void DoOpenBase(String FileName)
        {
            FileInfo ei = new FileInfo(FileName);
            if (!maner.Contains(ei.Extension))
            {
                alert("Файлы с расширением " + ei.Extension + " не обрабатываются" + Environment.NewLine +
                    "Пробуйте pdf,doc,txt,rtf");
                return;
            }
            AddFile(FileName);
            stat.Text = Path.GetFileName(FileName) + " добавлен";
        }

        public void alert(string s)
        {
            MessageBox.Show(s);
        }

        public void alert(int i)
        {
            MessageBox.Show(i.ToString());
        }


        private void DeletingFile_Click(object sender, EventArgs e)
        {
            string gd = "";
            DataGridViewSelectedCellCollection sc = dv.SelectedCells;
            for (int i = 0; i < sc.Count; i++)
            {
                int r = sc[i].RowIndex;
                gd = dv.Rows[r].Cells["id"].Value.ToString();
            }
            if ((gd == "") && (curguid == "")) return;
            if (texter.Text == "") return;
            if ((gd != "")&&(gd != null))
            {
                //QE("update path in Docs where id='" + gd + "'");
                DeleteFile(gd);
                return;
            }
            if ((curguid != "")&&(curguid != null))
            {
                //QE("update path in Docs where id='" + curguid + "'");
                DeleteFile(curguid);
                return;
            }
            GetDocs();
        }

        Dictionary<string, bool> RuStopMap;
        Dictionary<string, bool> EnStopMap;

        private void Form1_Load(object sender, EventArgs e)
        {
            ToolTip tp = new ToolTip();
            //tp.ToolTipTitle = "Сначала слова из запроса приводятся к словоформам и далее поиск осуществляется среди словоформ";
            tp.UseFading = true;
            tp.SetToolTip(Osnova, "Сначала слова из запроса приводятся к словоформам и далее поиск осуществляется среди словоформ");

            tabControl1.SelectedIndex = 1;

            openFileDialog1.InitialDirectory = (new DirectoryInfo(Application.ExecutablePath)).Parent.Parent.Parent.ToString();
            openFileDialog1.RestoreDirectory = true;
            openFileDialog1.Multiselect = false;
            openFileDialog1.FilterIndex = 0;

            DirectoryInfo di = new DirectoryInfo(Application.ExecutablePath).Parent.Parent.Parent;
            tmp_path = di.FullName + "\\Tmp.txt";

            ////======пока так
            RuStopMap = new Dictionary<string, bool>();
            EnStopMap = new Dictionary<string, bool>();

            string sPath = Application.StartupPath;

            string[] Words = File.ReadAllLines(di.FullName + "\\stop\\rustop.txt", Encoding.Default);
            foreach (string sStopWord in Words)
                RuStopMap[sStopWord] = true;
            Words = File.ReadAllLines(di.FullName + "\\stop\\enstop.txt", Encoding.Default);
            foreach (string sStopWord in Words)
                EnStopMap[sStopWord] = true;
            ////==========

        }

        private void button6_Click(object sender, EventArgs e)
        {
            QE("insert into Docs(path,id) VALUES('" +
                    @"C:\Users\НО\Documents\Visual Studio 2008\Projects\TxM\TxM\1.txt" + "',NEWID())");
        }


        #region TestPage
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                txtFilePath.Text = openFileDialog1.FileName;
                btnReadFile_Click(sender, e);
            }
        }

        private void btnReadFile_Click(object sender, EventArgs e)
        {
            XReader oReader = new XReader(txtFilePath.Text);
            richTextBox1.Text = oReader.Text;
            btnStemm_Click(sender, e);
        }

        public string Stemm(string slovo)
        {
            Regex enReg = new Regex(@"[A-Za-z0-9]");
            Regex ruReg = new Regex(@"[А-Яа-я0-9]");
            string sWord = slovo.ToLower();

            //stop words
            if (RuStopMap.ContainsKey(sWord) || EnStopMap.ContainsKey(sWord))
                return slovo;

            string sStem = string.Empty;
            if (enReg.IsMatch(sWord))
                sStem = (new EnglishWord(sWord)).Stem;
            else if (ruReg.IsMatch(sWord))
                sStem = (new RuStemming()).Stem(sWord);
            return sStem;
        }

        private void btnStemm_Click(object sender, EventArgs e)
        {
            string sText = richTextBox1.Text;
            lblUdkPos.Text = txtUdk.Text = string.Empty;
            lstStemm.Items.Clear();
            lstAuthors.Items.Clear();
            Regex enReg = new Regex(@"[A-Za-z0-9]");
            Regex ruReg = new Regex(@"[А-Яа-я0-9]");
            Regex reg = new Regex(@"[ ,;:\.\?!=\&\*\+()/]");
            Regex Udk = new Regex(@"УДК\s\d{2,3}\.\d{1,3}(\.\d{1,2})?(\s*:\s*\d{2,3}\.\d{1,3}(\.\d{1,2})?)*");
            Regex Author = new Regex(@"([А-Я]\.\s*)([А-Я]\.\s*)\s[А-Я][А-Яа-я]+");
            Dictionary<string, int> Map = new Dictionary<string, int>();
            Dictionary<string, int> MapWords = new Dictionary<string, int>();
            string[] Lines = sText.Split(new char[] { '\f', '\r', '\n' });
            int nLine = 0;
            foreach (string Line in Lines)
            {
                string sLine = Line;
                if (Author.IsMatch(Line))
                {
                    MatchCollection oMatches = Author.Matches(Line);
                    foreach (Match oMatch in oMatches)
                    {
                        string sPos = " (" + nLine.ToString() + ":" + oMatch.Index.ToString() + ")";
                        lstAuthors.Items.Add(oMatch.Value + sPos);
                    }
                    sLine = Author.Replace(Line, "");
                }

                if (Udk.IsMatch(sLine))
                {
                    Match oMatch = Udk.Match(sLine);
                    txtUdk.Text = oMatch.Value;
                    sLine = Udk.Replace(sLine, "");
                    lblUdkPos.Text = "(" + nLine.ToString() + ":" + oMatch.Index.ToString() + ")";
                }

                string[] Words = reg.Split(sLine);
                foreach (string Word in Words)
                {
                    if (Word.Length < 2)
                        continue;

                    string sWord = Word.ToLower();

                    //stop words
                    if (RuStopMap.ContainsKey(sWord) || EnStopMap.ContainsKey(sWord))
                        continue;

                    string sStem = string.Empty;
                    if (enReg.IsMatch(sWord))
                        sStem = (new EnglishWord(sWord)).Stem;
                    else if (ruReg.IsMatch(sWord))
                        sStem = (new RuStemming()).Stem(sWord);
                    if (sStem.Length > 0)
                    {
                        if (Map.ContainsKey(sStem))
                            Map[sStem]++;
                        else
                            Map[sStem] = 1;

                        //if (!MapWords.ContainsKey(sWord))
                        //MapWords[sWord]++;
                        //else
                        //  MapWords[sWord] = MapWords.ElementAt(Map[sStem]).Value;
                    }
                }
                nLine++;
            }
            int nCount = Map.Count();
            for (int i = 0; i < nCount; i++)
                lstStemm.Items.Add(Map.ElementAt(i).Key);
            int nCountW = MapWords.Count();
            for (int i = 0; i < nCountW; i++)
                lstGraphoids.Items.Add(MapWords.ElementAt(i).Key + " " + MapWords.ElementAt(i).Value.ToString());
        }

        public void Parse(string s, string docid)
        {
            string sText = s;
            Regex enReg = new Regex(@"[A-Za-z0-9]");
            Regex ruReg = new Regex(@"[А-Яа-я0-9]");
            Regex reg = new Regex(@"[ ,;:\.\?!=\&\*\+()/]");
            List<string> Map = new List<string>();
            List<string> MapKey = new List<string>();
            List<string> MapWords = new List<string>();
            List<string> MapWordsKey = new List<string>();
            //List<string> MapWordsExternalKey = new List<string>();
            string[] Lines = sText.Split(new char[] { '\f', '\r', '\n' });
            int cc = 0;
            foreach (string Line in Lines)
            {
                string[] Words = reg.Split(Line);
                foreach (string Word in Words)
                {
                    if (Word.Length < 2)
                        continue;

                    string sWord = Word.ToLower();
                    sWord = sWord.Replace((char)39, '_');

                    //stop words
                    if (RuStopMap.ContainsKey(sWord) || EnStopMap.ContainsKey(sWord))
                        continue;

                    string sStem = string.Empty;
                    if (enReg.IsMatch(sWord))
                        sStem = (new EnglishWord(sWord)).Stem;
                    else if (ruReg.IsMatch(sWord))
                        sStem = (new RuStemming()).Stem(sWord);
                    sStem = sStem.Replace((char)39, '_');
                    if (sStem.Length > 0)
                    {
                        //Guid g= new Guid();
                        string guid = "";// (new Guid()).ToString();

                        int kol = (int)QS("select COUNT(id) from Words where forma='" + sStem + "'");

                        //if (Map.Contains(sStem))
                        if (kol > 0)
                        {
                            guid = ((Guid)QS("select id from Words where forma='" + sStem + "'")).ToString();
                        }
                        else
                        {
                            QE("insert into Words(id,forma) VALUES(NEWID(),'" + sStem + "')");
                            guid = ((Guid)QS("select id from Words where forma='" + sStem + "'")).ToString();
                            //Map[sStem] = 1;
                        }
                        Map.Add(sStem);
                        MapKey.Add(guid);


                        string guidw = "";// (new Guid()).ToString();
                        int kolw = (int)QS("select COUNT(id) from Graphoids where graphoid='" + sWord + "'");
                        if (kolw > 0)
                        {
                            guidw = ((Guid)QS("select id from Graphoids where graphoid='" + sWord + "'")).ToString();
                        }
                        else
                        {
                            //guidw = (new Guid()).ToString();
                            //QE("insert into Graphoids(id,graphoid,wordid) VALUES('"+guidw+"','" + sWord + "','" + guid + "')");
                            QE("insert into Graphoids(id,graphoid,wordid) VALUES(NEWID(),'" + sWord + "','" + guid + "')");
                            guidw = ((Guid)QS("select id from Graphoids where graphoid='" + sWord + "' AND wordid='" + guid + "'")).ToString();
                        }

                        //string guido = "";
                        //int kolo = (int)QS("select COUNT(id) from Words_all where graphid='" + sWord + "'");
                        //if (kolo > 0)
                        //{
                        //    guidw = ((Guid)QS("select id from Graphoids where graphoid='" + sWord + "'")).ToString();
                        //}
                        //else
                        //{
                        cc++;
                        QE("insert into Words_all(id,graphid,docid,num) VALUES(NEWID(),'" + guidw + "','" + docid + "',"+cc.ToString()+")");
                        //guido = ((Guid)QS("select id from Graphoids where graphoid='" + sWord + "' AND wordid='" + guid + "'")).ToString();
                        //}

                        MapWords.Add(sWord);
                        MapWordsKey.Add(guidw);

                        //if (!MapWords.ContainsKey(sWord))
                        //    //MapWords[sWord]++;
                        //    //else
                        //    MapWords[sWord] = MapWords.ElementAt(Map[sStem]).Value;
                    }
                }
            }

            int i;
            for (i = 0; i < Map.Count; i++)
            {

            }
        }

        public void ReadText(string t)
        {
            // create reader & open file
            StreamReader tr = new StreamReader(t);
            //Textreader tr = new StreamReader("date.txt");
            // read a line of text
            Console.WriteLine(tr.ReadLine());
            // close the stream
            tr.Close();
        }

        public string NewDoc(string path, string text)
        {
            text = text.Replace((char)39, '_');
            //text = text.Replace('''', '_');
            int kol = (int)QS("select COUNT(id) from Docs where path='" + path + "'");
            string guid = "";
            if (kol == 0)
            {
                QE("insert into Docs(id,path,fulltext) VALUES(NEWID(),'" + path + "','" + text + "')");
                guid = ((Guid)QS("select id from Docs where path='" + path + "'")).ToString();
            }
            else
            {
                guid = ((Guid)QS("select id from Docs where path='" + path + "'")).ToString();
                QE("update Docs set path='" + path + "' where id='" + guid + "'");
            }
            return guid;
        }

        public void RemoveAllDocRelated(string docguid)
        {
            QE("delete from Words_all where docid='" + docguid + "'");
            QE("delete from UDK_all where docid='" + docguid + "'");
            QE("delete from Authors_all where docid='" + docguid + "'");
        }

        private void btnStemmingTest_Click(object sender, EventArgs e)
        {
            EnglishWord word = new EnglishWord(txtStemmIn.Text);
            txtStemmOut.Text = word.Stem;
        }

        private void btnRuStemmerTest_Click(object sender, EventArgs e)
        {
            RuStemming stemm = new RuStemming();
            txtStemmRuOut.Text = stemm.Stem(txxStemmRuIn.Text);
        }
        #endregion

        private void button9_Click(object sender, EventArgs e)
        {
            selectWords_Click(sender, e);
            tabControl1.SelectedIndex = 0;
        }

        private void selectWords_Click(object sender, EventArgs e)
        {
            QToDv("select distinct * from Words");
        }

        private void PutWords_Click(object sender, EventArgs e)
        {
            foreach (string p in lstStemm.Items)
            {
                object was = QS("select COUNT(id) from Words where forma='" + p + "'");
                if ((int)was == 0)
                {
                    QE("insert into Words(forma,id) VALUES('" + p + "',NEWID())");
                }
            }
        }



        private void dv_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewSelectedCellCollection sc = dv.SelectedCells;
            for (int i = 0; i < sc.Count; i++)
            {
                //alert(sc[i].Value.ToString());

                int r = sc[i].RowIndex;
                //string u = dv.Columns["id"].Row [r].ToString();
                string docid = dv.Rows[r].Cells["id"].Value.ToString();
                if (curguid != docid)
                {
                    curguid = docid;
                    PutText(docid);
                    InsertInfo(docid);
                }
            }
        }
        public void PutText(string docguid)
        {
            object obj = QS("select fulltext from Docs where id='" + docguid + "'");
            string str = (string)obj;
            texter.Text = str;
        }
        public void PutTextView(string docguid)
        {
            object obj = QS("select fulltext from Docs where id='" + docguid + "'");
            string str = (string)obj;
            podsv.Text = str;
        }

        public void InsertInfo(string uidoc)
        {
            Pathis.Text = (string)QS("select path from Docs where id='" + uidoc + "'");
            WordCount.Text = ((int)QS("select COUNT(Words_all.id) from Words_all where Words_all.docid='" + uidoc + "'")).ToString();
            string[] aus = (string[])QArr("select Authors.name from Authors_all,Authors where Authors_all.docid='" + uidoc + "' AND Authors_all.aid=Authors.id");
            string[] udks = (string[])QArr("select UDK.name from UDK_all,UDK where UDK_all.docid='" + uidoc + "' AND UDK_all.aid=UDK.id");
            int i;
            string s = "";
            Au.Text = ""; Udki.Text = "";
            Slova.Items.Clear(); Slovoforms.Items.Clear();
            if (aus != null)
            {
                for (i = 0; i < aus.Length; i++)
                {
                    s += "'" + aus[i] + "'";
                    if (i < aus.Length - 1) s += ", ";
                }
                Au.Text = s;
            }
            if (udks != null)
            {
                s = "";
                for (i = 0; i < udks.Length; i++)
                {
                    s += "'" + udks[i] + "'";
                    if (i < udks.Length - 1) s += ", ";
                }
                Udki.Text = s;
            }


            object[] ob = QArr("select Graphoids.graphoid from Words_all,Graphoids,Words where Words_all.docid='" + uidoc +
                "' AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id");
            aus = (string[])ob;
            udks = (string[])QArr("select Words.forma from Words_all,Graphoids,Words where Words_all.docid='" + uidoc +
                "' AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id");
            if (aus != null)
            {
                for (i = 0; i < aus.Length; i++)
                {
                    //s += "'" + aus[i] + "'";
                    //if (i < aus.Length - 1) s += ", ";
                    Slova.Items.Add(aus[i]);
                }
                //Slova.Text = s;
            }
            if (udks != null)
            {
                s = "";
                for (i = 0; i < udks.Length; i++)
                {
                    //s += "'" + udks[i] + "'";
                    //if (i < udks.Length - 1) s += ", ";
                    Slovoforms.Items.Add(udks[i]);
                }
                //Udki.Text = s;
            }
        }

        string curguid = "";
        private void ChangePath_Click(object sender, EventArgs e)
        {
            string gd = "";
            DataGridViewSelectedCellCollection sc = dv.SelectedCells;
            for (int i = 0; i < sc.Count; i++)
            {
                int r = sc[i].RowIndex;
                gd=dv.Rows[r].Cells["id"].Value.ToString();
            }
            if ((gd == "")&&(curguid == "")) return;
            if (texter.Text == "") return;
            if ((gd != "")&&(gd != null))
            {
                QE("update path in Docs where id='" + gd + "'");
                return;
            }
            if ((curguid != "")&&(curguid != null))
            {
                QE("update path in Docs where id='" + curguid + "'");
                return;
            }
        }

        DateTime lastchanged = DateTime.Now;
        private void stat_TextChanged(object sender, EventArgs e)
        {
            if (stat.Text != "")
                lastchanged = DateTime.Now;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (DateTime.Now > lastchanged.AddMilliseconds(4500)) stat.Text = "";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Pathis.Text = openFileDialog1.FileName;
                //ChangePath_Click(sender, e);
            }
        }









        private void Open1_Click(object sender, EventArgs e)
        {
            Open(txtFilePath.Text);
        }

        public void OpenSome(string now, string was)
        {
            if ((now == null) || (now == ""))
            {
                if ((was == null) || (was == ""))
                {
                }
                else
                {
                    Open(was);
                }
            }
            else
            {
                Open(now);
            }
        }

        public void Open(string f)
        {
            string s = (string)QS("select path from Docs where id='" + f + "'");
            Process process = new Process();
            process.StartInfo.FileName = @s;
            process.Start();
            return;
        }

        private void view_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        public string DetectDocGuid()
        {
            string gd = "";
            DataGridViewSelectedCellCollection sc = view.SelectedCells;
            for (int i = 0; i < sc.Count; i++)
            {
                gd = view.Rows[sc[i].RowIndex].Cells["id"].Value.ToString();
            }
            return gd;
        }
        string view_docguid = "";
        private void OpenEvery_Click(object sender, EventArgs e)
        {
            OpenSome(DetectDocGuid(), view_docguid);
        }

        private void view_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            view_docguid = DetectDocGuid();
            if((view_docguid!=null)&&(view_docguid!=""))
                PutTextView(view_docguid);
            //Podsvetka
            //
        }

        private void SearchWord_Click(object sender, EventArgs e)
        {
            string word = oneword.Text;
            //if (being_key.Checked == false)
            //{
            //    if (Osnova.Checked)
            //    {
            //        word = Stemm(word);
            //        QToView("select Docs.id as id,Docs.path as path,Graphoids.graphoid as slovo,Words_all.pos as pos,Words_all.stroka as strk,Words_all.stolb as stlb,Words.forma " +
            //            "from Docs,Words_all,Graphoids,Words where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id AND Words.forma='" + word + "'");
            //    }
            //    else
            //    {
            //        QToView("select Docs.id as id,Docs.path as path,Graphoids.graphoid as slovo,Words_all.pos as pos,Words_all.stroka as strk,Words_all.stolb as stlb " +
            //            "from Docs,Words_all,Graphoids where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.graphoid='" + word + "'");
            //    }
            //}
            //else
            //{

            //}

            //string final="";
            if (being_key.Checked)
            {
                int kol = 0;
                if (Osnova.Checked)
                {
                    word = Stemm(word);
                    kol = (int)QS("select COUNT(Words_all.id) " +
                        "from Docs,Words_all,Graphoids,Words where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id AND Words.forma='" + word + "'");
                 }
                else
                {
                    kol = (int)QS("select COUNT(Graphoids.id)"+
                        "from Docs,Words_all,Graphoids where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.graphoid='" + word + "'");
                }

                if (kol > 1)
                {
                    if (Osnova.Checked)
                    {
                        word = Stemm(word);
                        QToView("select Docs.id as id,Docs.path as path,Words.forma " +
                            "from Docs,Words_all,Graphoids,Words where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id AND Words.forma='" + word + "'");
                    }
                    else
                    {
                        QToView("select Docs.id as id,Docs.path as path,Graphoids.graphoid as slovo " +
                            "from Docs,Words_all,Graphoids where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.graphoid='" + word + "'");
                    }
                }
                else
                {
                    view.DataSource = null;
                }
            }
            else
            {
                if (Osnova.Checked)
                {
                    word = Stemm(word);
                    QToView("select Docs.id as id,Docs.path as path,Graphoids.graphoid as slovo,Words_all.num as num,Words_all.stroka as strk,Words_all.stolb as stlb,Words.forma " +
                        "from Docs,Words_all,Graphoids,Words where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id AND Words.forma='" + word + "'");
                }
                else
                {
                    QToView("select Docs.id as id,Docs.path as path,Graphoids.graphoid as slovo,Words_all.num as num,Words_all.stroka as strk,Words_all.stolb as stlb " +
                        "from Docs,Words_all,Graphoids where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.graphoid='" + word + "'");
                }
            }



        }

        private void Comb_AND_Click(object sender, EventArgs e)
        {
            AnyOrAnd(comb1.Text+" AND "+comb2.Text);
        }

        private void Any_Click(object sender, EventArgs e)
        {
            AnyOrAnd(Anya.Text);
        }

        public void AnyOrAnd(string q)
        {
            string[] all = q.Split(' ');
            q = q.ToLower();
            string[] words=new string[all.Length];
            string[] meg = new string[all.Length];
            int pos=0,kol=0;
            string newword = "";
            while((pos<q.Length)&&(true))
            {
                while ((pos < q.Length) && (q[pos] == ' ')) pos++;
                newword = "";
                while ((pos < q.Length) && (q[pos]!=' '))
                {
                    newword += q[pos]; pos++;
                }
                kol++; words[kol - 1] = newword;
                pos++; newword = " ";
                while ((pos < q.Length) && (q[pos] == ' ')) pos++;
                while ((pos < q.Length) && (q[pos] != ' '))
                {
                    newword += q[pos]; pos++;
                }
                pos++; newword += " ";
                meg[kol] = newword;
            }

            List<string> res = new List<string>();
            //string totalq = "";
            string query2 = "";
            int i,j,ii;
            bool b=false;
            if (Osnova.Checked)
            {
                for(i=0;i<kol;i++)
                    words[i] = Stemm(words[i]);
                string query = "select Docs.id as id " +
                    "from Docs,Words_all,Graphoids,Words where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id AND ";
                
                for(i=0;i<kol;i++)
                {
                    query2 = query + " Words.forma='" + words[i] + "'";
                    string[] mew = (string[])QArr(query2);
                    //if (mew[0] != null)
                    {
                        if (i > 0)
                        {
                            if ((meg[i][1] == 'a') && (meg[i][2] == 'n') && (meg[i][3] == 'd'))
                            {
                                for (ii = res.Count - 1; ii >= 0; ii--)
                                {
                                    b = false;
                                    for (j = mew.Length - 1; (!b) && (j >= 0); j--)
                                    {
                                        if (res[ii] == mew[j]) b = true;
                                    }
                                    if (!b) res.RemoveAt(ii);
                                }
                            }
                            if ((meg[i][1] == 'o') && (meg[i][2] == 'r'))
                            {
                                for (ii = mew.Length - 1; ii >= 0; ii--)
                                {
                                    b = false;
                                    for (j = res.Count - 1; (!b) && (j >= 0); j--)
                                    {
                                        if (res[j] == mew[ii]) b = true;
                                    }
                                    if (!b) res.Add(mew[ii]);
                                }
                            }
                        }
                        else
                        {
                            for (ii = mew.Length - 1; ii >= 0; ii--)
                            {
                                res.Add(mew[ii]);
                            }
                        }
                    }
                }
            }
            else
            {
                string query = "select Docs.id as id " +
                    "from Docs,Words_all,Graphoids where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND ";

                for(i=0;i<kol;i++)
                {
                    query2 = query + "Graphoids.graphoid='" + words[i] + "'";
                    string[] mew = (string[])QArr(query2);
                    //if (mew[0] != null)
                    {
                        if (i > 0)
                        {
                            if ((meg[i][1] == 'a') && (meg[i][2] == 'n') && (meg[i][3] == 'd'))
                            {
                                for (ii = res.Count - 1; ii >= 0; ii--)
                                {
                                    b = false;
                                    for (j = mew.Length - 1; (!b) && (j >= 0); j--)
                                    {
                                        if (res[ii] == mew[j]) b = true;
                                    }
                                    if (!b) res.RemoveAt(ii);
                                }
                            }
                            if ((meg[i][1] == 'o') && (meg[i][2] == 'r'))
                            {
                                for (ii = mew.Length - 1; ii >= 0; ii--)
                                {
                                    b = false;
                                    for (j = res.Count - 1; (!b) && (j >= 0); j--)
                                    {
                                        if (res[j] == mew[ii]) b = true;
                                    }
                                    if (!b) res.Add(mew[ii]);
                                }
                            }
                        }
                        else
                        {
                            for (ii = mew.Length - 1; ii >= 0; ii--)
                            {
                                res.Add(mew[ii]);
                            }
                        }
                    }
                }
            }
            DataTable dt=new DataTable();
            DataColumn dc1=new DataColumn("id");
            DataColumn dc2=new DataColumn("path");
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            foreach (string id in res)
            {
                object[] vals={id,(string)QS("select path from Docs where id='" + id + "'")};
                dt.Rows.Add(vals);
            }
            view.DataSource = dt;
            SizeAll(view);

            

        }

        private void TwoClose_Click(object sender, EventArgs e)
        {
            Company(w1.Text + " " + w2.Text);
        }

        private void SomeClose_Click(object sender, EventArgs e)
        {
            Company(wordstogether.Text);
        }

        char[] v = new char[] { ',',';',':','\\','.','\\','?','!','=','\\','&','\\','*','+','(',')','/'};
        public void Company(string p)
        {
            int i,j,k;
            while(p.IndexOf("  ")>=0)
                p = p.Replace("  ", " ");
            for(i=0;i<v.Length;i++)
            while(p.Contains(""+v[i]))
                p = p.Replace("" + v[i], "");

            string[] words = p.Split(' ');
            if(words.Length==0)return;
            //DataTable ddt = new DataTable();
            //DataColumn dc1 = new DataColumn("id");
            //DataColumn dc2 = new DataColumn("path");
            //DataColumn dc3 = new DataColumn("num");
            //ddt.Columns.Add(dc1);
            //ddt.Columns.Add(dc2);
            //ddt.Columns.Add(dc3);

            string query = "select Docs.id as id,Docs.path as path,Words_all.num " +
                "from Docs,Words_all,Graphoids where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.graphoid='";
            if (Osnova.Checked)
            {
                query = "select Docs.id as id,Docs.path as path,Words_all.num " +
                    "from Docs,Words_all,Graphoids,Words where Docs.id=Words_all.docid AND Words_all.graphid=Graphoids.id AND Graphoids.wordid=Words.id AND Words.forma='";
            }

            //0

            DataTable ddt=new DataTable();
            if (Osnova.Checked)
            {
                ddt=QueryTable(query+Stemm(words[0])+"'");
                //foreach(DataRow dr in dt)
                //{
                //    dr.ItemArray[0].ToString();
                //}
            }
            else
            {
                ddt = QueryTable(query + words[0] + "'");
            }

            DataTable dt=new DataTable();
            bool b=false;
            string id,pt,nm;
            string id0,pt0,nm0;
            for (k = 1; k < words.Length; k++)
            {
                if (Osnova.Checked)
                {
                    dt = QueryTable(query + Stemm(words[k]) + "'");
                }
                else
                {
                    dt = QueryTable(query + words[k] + "'");
                }
                //foreach (DataRow dr in ddt)
                for(i=ddt.Rows.Count-1;i>=0;i--)
                {
                    id0=ddt.Rows[i].ItemArray[0].ToString();
                    //pt0=ddt.Rows[i].ItemArray[1].ToString();
                    nm0=ddt.Rows[i].ItemArray[2].ToString();
                    b = false;
                    for (j = dt.Rows.Count - 1; (!b) && (j >= 0); j--)
                    {
                        id=dt.Rows[j].ItemArray[0].ToString();
                        //pt=dt.Rows[j].ItemArray[1].ToString();
                        nm=dt.Rows[j].ItemArray[2].ToString();
                        if ((id == id0) && ((nm0 == "") || (nm == "") || (Int32.Parse(nm0) == Int32.Parse(nm) - k)))
                            b = true;
                    }
                    if (!b) ddt.Rows.RemoveAt(i);
                }
            }

            ddt.Columns.Remove("num");

            view.DataSource = ddt;
            SizeAll(view);


            //foreach (string id in res)
            //{
            //    object[] vals = { id, (string)QS("select path from Docs where id='" + id + "'") };
            //    dt.Rows.Add(vals);
            //}

        }



    }
}
